/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: PointLengthFilter.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.view;

import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;

/**
 * ================================================
 * 描   述：输入小数位数限制过滤
 * ================================================
 */

public class PointLengthFilter implements InputFilter {
    /**
     * 输入框小数的位数  示例保留一位小数
     */
    private int DECIMAL_DIGITS = 1;

    public void setDecimalLength(int length){
        DECIMAL_DIGITS = length;
    }

    public CharSequence filter(CharSequence source, int start, int end,
                               Spanned dest, int dstart, int dend) {
        try{
            // 删除等特殊字符，直接返回
            if ("".equals(source.toString())) {
                return null;
            }

            if(DECIMAL_DIGITS==0){
                if (source.equals(".")){
                    return "";
                }
                return null;
            }

            if (dest.length() == 0 && source.equals(".")) {
                return "0.";
            }

            String dValue = dest.toString();
            if (dend<=dValue.indexOf(".")){
                return source;
            }else{

                String[] splitArray = dValue.split("\\.");
                if (splitArray.length > 1&&dValue.contains(".")) {
                    String dotValue = splitArray[1];
                    if (dotValue.length()<DECIMAL_DIGITS) {

                        if (dotValue.length()<DECIMAL_DIGITS) {
                            int diff = DECIMAL_DIGITS - dotValue.length();
                            if (source.length()>diff) {
                                return source.subSequence(0,diff);
                            }else{
                                return source;
                            }
                        }else {
                            return "";
                        }
                    }else{
                        return "";
                    }
                }else{
                    return source;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return TextUtils.isEmpty(dest.toString())?source:"";
    }
}
